<template>
  <div class="flexContent">
    <!-- 新增入库 -->
    <h3>入库信息</h3>
    <div class="add">
      <el-button class="addBtn" v-show="!detail.isDetail" @click="submitForm">调订单</el-button>
    </div>
    <div class="table">
      <el-form ref="formDataref" :model="formData">
        <el-table border class="tablebox" :data="formData.tableData" max-height="510" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="commodityName"
            :min-width="elTableAdaptationWidth('commodityName', formData.tableData)" label="商品名称" />
          <el-table-column property="barCode" align="center" label="商品条码" />
          <el-table-column property="commodityStandard" align="center" label="商品规格" />
          <el-table-column property="bigPacking" align="center" label="大包装" />
          <el-table-column align="center" prop="warehouseName" label="仓库" />
          <el-table-column align="center" prop="regionName" label="区域">
            <template v-slot="{ row }">
              {{ row.regionName ? row.regionName : "-" }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="positionId" label="仓位">
            <template slot-scope="scope">
              <el-form-item v-if="!detail.isDetail" :prop="'tableData.' + scope.$index + '.positionId'"
                :rules="tableRules.positionId">
                <el-select ref="inputaldQty" v-model="scope.row.positionId" placeholder="" popper-class="eloption"
                  size="small" style="width: 100%" clearable filterable
                  @click.native="getPositonList(scope.row, scope.$index)"
                  @change="selectPositionId(scope.row, scope.$index)">
                  <el-option v-for="item in scope.row.positionList" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
              <span v-if="detail.isDetail">{{ scope.row.positionName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="inboundCount" label="入库数量" />
          <el-table-column v-if="detail.isDetail" align="center" prop="batchNumber"
            :min-width="elTableAdaptationWidth('batchNumber', formData.tableData)" label="批次号" />
          <el-table-column property="manufactureTime" align="center" label="生产日期">
            <template v-slot="{ row }">
              <span>{{ row.manufactureTime | parseTime('YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formDataref')">确定</el-button>
    </div>
    <el-dialog title="调退货单" :visible.sync="dialogTableVisible" width="80%">
      <el-table border :data="gridData1" ref="multipleTable" row-key="id" class="tablebox" height="500px"
        @row-click="handlerClick" @selection-change="selFn" size="medium">
        <el-table-column type="selection" align="center" width="55" reserve-selection />
        <el-table-column property="returnsNumber" align="center" label="退货编号" />
        <el-table-column property="warehouseName" align="center" label="退货仓库" />
        <el-table-column property="commodityName" align="center" label="商品名称" />
        <el-table-column property="barCode" align="center" label="商品条码" />
        <el-table-column property="commodityStandard" align="center" label="商品规格" />
        <el-table-column property="returnNum" align="center" label="退货数量" />
        <el-table-column property="batchNumber" align="center" label="批次号" />
        <el-table-column property="manufactureTime" align="center" label="生产日期">
          <template v-slot="{ row }">
            <span>{{ row.manufactureTime | parseTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column property="examineTime" align="center" label="审核日期">
          <template v-slot="{ row }">
            <span>{{ row.examineTime | parseTime }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取消</el-button>
        <el-button class="addBtn" @click="confirmFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBuyReturnsRecord,
  returnWareInbound,
  selectForInbound,
  mergeBuyReturnsRecord
} from "@/api/warehouse";
export default {
  name: "ReturnTOwarehouseAdd",
  data() {
    return {
      dialogTableVisible: false,
      firstSupplierList: [],
      sform: {
        remake: "", // 备注
        warehouseName: "",
        takeRemake: "",
        warehouseId: "",
        detailsList: [],
        buyOrderId: "",
        takeDeliveryId: "",
        number: "",
        supplierName: "",
      },
      formData: {
        takeRemake: "",
        warehouseName: "",
        warehouseId: "",
        tableData: [],
      },
      positionList: [],
      pickList: [],
      tableRules: {
        positionId: [{ required: true, message: "仓位不能为空" }],
      },
      gridData1: [],
      gridData2: [],
      detail: {
        isDetail: false,
        id: "",
      },
      disabledList: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
    };
  },
  created() {
    this.detail.id = this.$route.query.id;
    this.detail.isDetail = !!this.$route.query.id;

  },
  methods: {
    async submitForm(formName) {
      const res = await getBuyReturnsRecord({ ...this.page });
      if (res.code === 200) {
        console.log('res.', res.data);
        this.gridData1 = res.data.list;
        this.page.total = res.data.total
      }
      this.dialogTableVisible = true;
    },
    submitData(formName) {
      if (this.formData.tableData.length <= 0)
        return this.$message.warning("请先选择订单");
      this.$refs.formDataref.validate(async (valid) => {
        if (valid) {
          console.log(this.formData, "formData");
          this.sform.detailsList = [];
          this.formData.tableData.forEach((item) => {
            this.sform.detailsList.push({
              commodityId: item.commodityId,
              warehouseId: item.warehouseId,
              regionId: item.regionId,
              positionId: item.positionId,
              batchNumber: item.batchNumber,
              manufactureTime: item.manufactureTime,
              inboundCount: item.inboundCount,
              bigPacking: item.bigPacking,
              ids: item.ids,
            });
          });
          console.log(this.sform, "this.sform");
          const res = await returnWareInbound({ list: this.sform.detailsList });
          if (res.code === 200) {
            this.$message.success("添加成功");
            this.closeTag("returnTOwarehouse");
          } else {
            // this.$message.error(res.message);
          }
        }
      });
    },
    async confirmFn() {
      this.formData.tableData = [];
      const res = await mergeBuyReturnsRecord({ idList: this.pickList });
      if (res.code === 200) {
        console.log('res.data', res.data);
        this.formData.tableData = res.data;
        this.dialogTableVisible = false;
        this.disabledList = []
      } else {
        // this.$message.warning(res.data.message);
      }
    },
    cancelFn() {
      this.dialogTableVisible = false;
    },
    cancelBtn() {
      this.closeTag("receiving");
    },
    async getPositonList(row, index) {
      // console.log(row, 'row')
      console.log("获取列表");
      // if (this.formData.tableData[index].positionList) return
      if (!row.regionId)
        return this.$message.warning("该商品没有绑定区域，请先绑定区域");
      const res = await selectForInbound({
        warehouseId: row.warehouseId,
        regionId: row.regionId,
      });
      if (res.code === 200) {
        let arr = res.data;
        arr = arr.filter(
          (item1) =>
            !this.disabledList.some(
              (item) =>
                item === item1.id &&
                item1.id !== this.formData.tableData[index].positionId
            )
        );
        if (arr.length <= 0)
          this.$message.warning("该区域没有仓位了，请先创建仓位");
        // if (this.formData.tableData[index].positionList)
        this.$set(this.formData.tableData[index], "positionList", arr);
        console.log(
          this.formData.tableData[index].positionList,
          "this.positionList"
        );
      }
    },
    selectPositionId(row, index) {
      // console.log(row.positionId, 'val')
      console.log("调用了");
      const selId = row.positionId;
      // this.disabledList =
      const arr = this.formData.tableData
        .filter((item) => {
          return item.positionId;
        })
        .map((item) => item.positionId);
      this.disabledList = [...new Set(arr)];
      console.log(this.disabledList, "this.disabledList");
      const flag = this.formData.tableData.some(
        (item, inx) => item.positionId === selId && inx !== index
      );
      if (flag) {
        //
        this.$message.warning("该仓位已被选择");
        this.$set(this.formData.tableData[index], "positionId", "");
      }
    },
    handlerClick(row) {
      console.log('row', row);
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    async selFn(selection) {
      this.pickList = selection.map((item) => item.id);
      console.log(this.pickList, "selFn");
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.gridData1 = []
      this.submitForm();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.gridData1 = []
      this.submitForm();
    },
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}
</style>
